# !/usr/bin/env python
# coding: utf-8


from _datetime import datetime
import cv2


# 视频处理
def process(file, fname):
    # camera = cv2.VideoCapture(0)  # 参数0表示第一个摄像头
    camera = cv2.VideoCapture(file)
    # 参数设置，监测矩形区域
    # rectangleX =int(camera.get(cv2.CAP_PROP_FRAME_WIDTH)) # 矩形最左点x坐标
    rectangleX = 450
    rectangleXCols = 800  # 矩形x轴上的长度
    # rectangleY = int(camera.get(cv2.CAP_PROP_FRAME_HEIGHT)) # 矩形最上点y坐标
    rectangleY = 260  # 矩形最上点y坐标
    rectangleYCols = 500  # 矩形y轴上的长度
    KeyFrame = 15  # 取关键帧的间隔数，根据视频的帧率设置，我的视频是16FPS
    counter = 1  # 取帧计数器
    pre_frame = None  # 总是取视频流前一帧做为背景相对下一帧进行比较
    threshold=2000

    # 添加计时器字典
    timers = {
        "counter": 0,
        'read': 0,
        'write': 0,
        'handle': 0,
        "all": 0
    }

    # 判断视频是否打开
    if not camera.isOpened():
        print('视频文件打开失败！')

    width = int(camera.get(cv2.CAP_PROP_FRAME_WIDTH))
    height = int(camera.get(cv2.CAP_PROP_FRAME_HEIGHT))
    fps = int(camera.get(cv2.CAP_PROP_FPS))
    KeyFrame = fps
    counterNum = int(camera.get(cv2.CAP_PROP_FRAME_COUNT))
    print(f'视频尺寸（高，宽）总帧数: ({height} , {width}), {counterNum},fps {fps}')

    videowrite = cv2.VideoWriter(file.replace('.', '_result.'),
                                 cv2.VideoWriter_fourcc(*"mp4v"),
                                 KeyFrame // 5,
                                 (width, height))

    if rectangleXCols == 0:
        rectangleXCols = width - rectangleX
    if rectangleYCols == 0:
        rectangleYCols = height - rectangleY
    start_time = datetime.now()
    print('{} 开始处理文件： {}'.format(start_time.strftime('%H:%M:%S'), fname))
    while True:
        read_start_time = datetime.now()
        grabbed, frame_lwpCV = camera.read()  # 读取视频流
        timers["read"] = int((datetime.now() - read_start_time).total_seconds() * 1000)  # 转换为毫秒

        if grabbed:
            if counter % KeyFrame == 0:
                # if not grabbed:
                #     print('{} 完成处理文件： {} 。。。  '.format(datetime.now().strftime('%H:%M:%S'),fname))
                #     break
                handle_start_time = datetime.now()
                gray_lwpCV = cv2.cvtColor(frame_lwpCV, cv2.COLOR_BGR2GRAY)  # 转灰度图
                gray_lwpCV = gray_lwpCV[rectangleY:rectangleY + rectangleYCols, rectangleX:rectangleX + rectangleXCols]
                cv2.rectangle(frame_lwpCV, (rectangleX, rectangleY),
                              (rectangleX + rectangleXCols, rectangleY + rectangleYCols), (0, 255, 0),
                              2)  # 用绿色矩形框显示监测区域
                # cv2.imshow('lwpCVWindow', frame_lwpCV)  # 显示视频播放窗口，开启消耗时间大概是3倍
                # cv2.waitKey(1)
                gray_lwpCV = cv2.GaussianBlur(gray_lwpCV, (21, 21), 0)
                if pre_frame is None:
                    pre_frame = gray_lwpCV
                    pre_frame_C = frame_lwpCV
                else:

                    handle_start_time = datetime.now()
                    img_delta = cv2.absdiff(pre_frame, gray_lwpCV)


                    thresh = cv2.threshold(img_delta, 25, 255, cv2.THRESH_BINARY)[1]
                    thresh = cv2.dilate(thresh, None, iterations=2)
                    contours, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
                    frame_tmp = pre_frame_C.copy()
                    area = 0
                    for x in contours:
                        countarea = cv2.contourArea(x)
                        area = area + countarea
                    timers['handle'] = int((datetime.now() - handle_start_time).total_seconds() * 1000)  # 转换为毫秒
                    write_start_time = datetime.now()

                    # if area>threshold:
                    #     cv2.putText(frame_tmp, 'warn index  %s' % area, (rectangleX, rectangleY),cv2.FONT_HERSHEY_SIMPLEX, 2,(0, 0, 255), 2)
                    # else:
                    #     cv2.putText(frame_tmp, 'warn index  %s' % area, (rectangleX, rectangleY), cv2.FONT_HERSHEY_SIMPLEX,
                    #                 2, (55, 255, 155), 2)
                    # cv2.imshow('lwpCVWindow', frame_tmp)  # 显示视频播放窗口，开启消耗时间大概是3倍
                    # cv2.waitKey(1)
                    # cv2.imwrite(
                    #         'data/image/' + fname + '_'  + f"f{counter}_w{area}" + '.jpg',
                    #         frame_tmp)
                    # videowrite.write(frame_tmp)
                    # print(f"监测到落石,程度{count}", datetime.now().strftime('%H:%M:%S'))

                    pre_frame = gray_lwpCV
                    pre_frame_C = frame_lwpCV
                    timers['write'] = int((datetime.now() - write_start_time).total_seconds() * 1000)  # 转换为毫秒
                    timers['counter'] = counter
                    timers['all'] = int((datetime.now() - read_start_time).total_seconds() * 1000)  # 转换为毫秒
                    print(
                        "[INFO] handle frame:{}/{} time:{} ms (read:{}ms handle:{}ms write:{}ms)".
                        format(timers["counter"],
                               counterNum,
                               timers["all"],
                               timers['read'],
                               timers['handle'],
                               timers['write']))
            counter += 1
            # key = cv2.waitKey(1) & 0xFF
            # if key == ord('q'):
            #     break

        else:
            end_time = datetime.now()
            print('{} 完成处理文件： {}  耗时：{}'.format(end_time.strftime('%H:%M:%S'), fname, end_time - start_time))
            break
    camera.release()
    # cv2.destroyAllWindows() #  与上面的imshow对应


if __name__ == "__main__":
    # fname = file.split('\\')[-1].replace('.mp4', '')
    file = "data/suidao_stable.mp4"
    fname = "suidao"
    process(file, fname)
